package com.bblocks.Interceptor;

import com.bblocks.common.auth.AccessRole;
import com.bblocks.common.Constant;
import com.bblocks.enums.AppTypeEnum;
import com.bblocks.enums.SysEnum;
import com.bblocks.exception.ServiceException;
import com.bblocks.pojo.ComUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: Mei
 *
 * 登录角色拦截器
 * @Date: created in 2019/1/10 14:12.
 */
@Slf4j
@Component
public class AccessRoleInterceptor implements HandlerInterceptor {

    /**
     *	 进入拦截器就执行的方法
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		ComUser userInfo = (ComUser)request.getAttribute(Constant.USER);

		AccessRole accessRole;
        if (handler instanceof HandlerMethod)
        {
			accessRole = ((HandlerMethod) handler).getMethodAnnotation(AccessRole.class);
        }
        else
        {
            return true;
        }

        if(accessRole == null)
        	return true;

		AppTypeEnum[] needRoles = accessRole.role();//当前需要的
		Integer appType = userInfo.getAppType();//用户有的，肯定有

		if(checkContain(AppTypeEnum.getAppTypeEnum(appType),needRoles)){
			return true;
		}else
			throw new ServiceException(SysEnum.PERMISSION_DENIED);
    }

    private boolean checkContain(AppTypeEnum appType,AppTypeEnum[] needRoles){
		for(AppTypeEnum one:needRoles){
			if(one == AppTypeEnum.All){
				return true;
			}else if(one == appType){
				return true;
			}
		}
		return false;
	}
}
